<template>
  <div class="SensorCont">
    <statistics-senor v-if="staticActive"></statistics-senor>

    <!-- 实时更新异常传感器 -->
    <div class="infoArea">
      <div class="infoCont">
        传感器
        <div class="infoSorId">{{curID}}</div>状态异常请尽快处理
      </div>
    </div>
    <!-- 搜索按钮和图标按钮控件 -->
    <div class="controlCont">
      <div
        :class="['controlSearch',searchActive?'controlSearch-active':'']"
        @click="searchActive = !searchActive"
      ></div>
      <div
        :class="['controlStatic',staticActive?'controlStatic-active':'']"
        @click="staticActive = !staticActive"
      ></div>
    </div>
    <!-- 搜索区域 -->
    <div class="searchArea" v-if="searchActive">
      <input
        type="number"
        min="1"
        max="10000"
        class="inputLable"
        placeholder="请输入传感器ID"
        v-model="sensorId"
      />
      <div class="searchWord">
        <div class="getButton" @click="getData">搜索</div>
        <div class="restButton" @click="resetData"></div>
      </div>
    </div>

    <!-- 图例显示 -->
    <div class="map-legend"></div>
    <!-- 指北针显示 -->
    <div class="map-compass"></div>
  </div>
</template>

<script>
import StatisticsSenor from "../Statistics/StatisticsSenor.vue";
// 请求报警数据
import { alarmData, SensorById } from "../../../../api/gis/layer";

import { Fill, Stroke, Style, Icon, Circle as CircleStyle } from "ol/style";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";

import { SensorArea } from "../../../../api/gis/layer";

import Feature from "ol/Feature.js";
import Point from "ol/geom/Point.js";
import { getVectorContext } from "ol/render.js";
import { easeOut } from "ol/easing.js";
import { unByKey } from "ol/Observable.js";
import { Message } from "element-ui";
let intervalKey, intervalKey1, intervalKey2;
let flag = true;

export default {
  props: {
    SensorMap: Object,
    BarName: String
  },
  components: {
    StatisticsSenor
  },
  data() {
    return {
      curID: undefined,
      sensorId: "",
      sensorIDList: [],
      searchActive: false,
      staticActive: true
      // searchSensor: {}
    };
  },
  mounted() {
    this.handleDrawSensorLayer();
    flag = true;

    // 异常传感器实时轮回更新显示
    this.intervalFuc();
    this.animationFun();
  },
  beforeDestroy() {
    // 关闭动态效果定时器
    if (intervalKey) {
      flag = false;
      clearInterval(intervalKey);
    }
    // 关闭间隔请求预警列表数据定时器
    if (intervalKey1) {
      clearInterval(intervalKey1);
    }
    // 关闭循环显示预警传感器定时器
    if (intervalKey2) {
      clearInterval(intervalKey2);
    }
    this.dispose();
  },
  methods: {
    // 搜索操作
    getData() {
      // 输入校验
      if (typeof Number(this.sensorId) == "string") return;

      SensorById({ sorId: Number(this.sensorId) }).then(res => {
        if (res.code === 200 && res.data.rows.length == 1) {
          this.$emit("SensorZoomTo", res.data.rows[0]);
        } else {
          Message({
            message: "未查询到" + this.sensorId + "传感器数据!",
            type: "error"
          });
          console.log("未查询到" + this.sensorId + "传感器数据!");
        }
      });
    },
    // 重置操作
    resetData() {
      this.sensorId = "";
      this.$emit("SensorBackTo");
    },
    //每隔10分钟请求报警接口
    animationFun() {
      intervalKey1 = setInterval(() => {
        that.intervalFuc();
      }, 600000); //10分
    },
    //每隔1秒轮巡传感器id组
    intervalFuc() {
      alarmData().then(res => {
        if (res.data && res.data.rows && res.data.rows.length > 0) {
          this.sensorIDList = res.data.rows;
        }
        // 循环显示查询到的传感器的id
        let j = 0;
        intervalKey2 = setInterval(() => {
          if (j < this.sensorIDList.length) {
            this.curID = this.sensorIDList[j++];
          } else {
            j = 0;
          }
        }, 2000);
      });
    },

    // 关闭组件销毁传感器正常异常图层
    dispose() {
      const layernormal = this.findLayerById("layernormal");
      this.SensorMap.removeLayer(layernormal);
      const layerwarning = this.findLayerById("layerwarning");
      this.SensorMap.removeLayer(layerwarning);
    },
    // 通过Id查询目标图层
    findLayerById(id) {
      const layers = this.SensorMap.getLayers();
      let res;
      layers.array_.forEach(layer => {
        if (layer.values_.id && layer.values_.id === id) {
          res = layer;
        }
      });
      return res;
    },
    // 加载传感器图层信息
    handleDrawSensorLayer() {
      SensorArea().then(res => {
        if (res.code === 200) {
          // 筛选监测正常传感器数据
          const NormalFeatures = [];
          // 筛选监测异常传感器数据
          const WarningFeatures = [];
          res.data.rows.forEach(item => {
            const styleNormal = new Style({
              image: new Icon({
                anchorXUnits: "fraction",
                anchorYUnits: "fraction",
                src: require("../../../../assets/img/OneMap/正常传感器.png")
              })
            });
            const styleWarning = new Style({
              image: new Icon({
                anchorXUnits: "fraction",
                anchorYUnits: "fraction",
                src: require("../../../../assets/img/OneMap/预警传感器.png")
              })
            });
            // 筛选监测正常和监测异常
            if (item.ifAlarm === 1 && item.ifFault === 1) {
              const NormalFeature = new Feature({
                geometry: new Point([item.longitude, item.latitude])
              });
              NormalFeature.set("props", item);
              NormalFeature.setStyle(styleNormal);
              NormalFeatures.push(NormalFeature);
            } else {
              const WarningFeature = new Feature({
                geometry: new Point([item.longitude, item.latitude])
              });
              WarningFeature.set("props", item);
              WarningFeature.setStyle(styleWarning);
              WarningFeatures.push(WarningFeature);
            }
          });
          // 单独添加正常传感器图层
          const sourceNormal = new VectorSource({
            wrapX: false,
            features: NormalFeatures
          });
          const layerNormal = new VectorLayer({
            source: sourceNormal
          });
          layerNormal.set("id", "layernormal");
          this.SensorMap.addLayer(layerNormal);
          // 单独添加异常传感器图层
          const sourceWarning = new VectorSource({
            wrapX: false,
            features: WarningFeatures
          });
          const layerWarning = new VectorLayer({
            source: sourceWarning
          });
          layerWarning.set("id", "layerwarning");
          this.SensorMap.addLayer(layerWarning);
          // 找到地图：谷歌地图
          const allLayers = this.SensorMap.getLayers();
          const tileLayer = allLayers.array_[0];

          // 定义动态渲染方法
          const duration = 3000;
          const that = this; //使用当前map
          function flash(feature) {
            const start = Date.now();
            const flashGeom = feature.getGeometry().clone();
            const listenerKey = tileLayer.on("postrender", animate);
            function animate(event) {
              if (!flag) {
                return;
              }
              const frameState = event.frameState;
              const elapsed = frameState.time - start;
              if (elapsed >= duration) {
                unByKey(listenerKey);
                return;
              }
              const vectorContext = getVectorContext(event);
              const elapsedRatio = elapsed / duration;
              // radius will be 5 at start and 30 at end.
              const radius = easeOut(elapsedRatio) * 25 + 5;
              const opacity = easeOut(1 - elapsedRatio);
              const style = new Style({
                image: new CircleStyle({
                  radius: radius,
                  stroke: new Stroke({
                    color: "rgba(255, 0, 0, " + opacity + ")",
                    width: 0.25 + opacity
                  }),
                  fill: new Fill({
                    color: "rgba(255,0,0,0.3)"
                  })
                })
              });
              vectorContext.setStyle(style);
              vectorContext.drawGeometry(flashGeom);
              that.SensorMap.render();
            }
          }
          sourceWarning.on("addfeature", function(e) {
            flash(e.feature);
          });

          // 利用定时器添加监测异常图层
          intervalKey = setInterval(() => {
            sourceWarning.clear();
            sourceWarning.addFeatures(WarningFeatures);
          }, 1000);
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.SensorCont {
  width: 100%;
  height: 100%;
  .infoArea {
    position: absolute;
    left: 100px;
    top: 100px;
    width: 380px;
    height: 60px;
    background: url("../../../../assets/img/Home/预警提示.png") no-repeat;
    background-size: 100% 100%;
    .infoCont {
      margin-left: 60px;
      height: 60px;
      line-height: 60px;
      display: flex;
      direction: row;
      font-family: "AlibabaPuHuiTi-2-5-Bold";
      font-size: 18px;
      font-weight: 600;
      font-style: italic;
      font-stretch: normal;
      letter-spacing: 0px;
      color: #f2a742;
      .infoSorId {
        margin-left: 10px;
        margin-right: 10px;
        color: red;
        width: 47px;
        text-align: center;
      }
    }
  }
  .controlCont {
    position: absolute;
    top: 100px;
    right: 70px;
    width: 124px;
    height: 52px;
    display: flex;
    direction: row;
    justify-content: space-between;
    .controlSearch {
      width: 52px;
      height: 52px;

      background: url("../../../../assets/img/Home/搜索1.png") no-repeat;
      background-size: 100% 100%;
      cursor: pointer;
    }
    .controlSearch-active {
      background: url("../../../../assets/img/Home/搜索2.png") no-repeat;
      background-size: 100% 100%;
    }
    .controlStatic {
      width: 52px;
      height: 52px;

      background: url("../../../../assets/img/Home/图表打开按钮.png") no-repeat;
      background-size: 100% 100%;
      cursor: pointer;
    }
    .controlStatic-active {
      background: url("../../../../assets/img/Home/图表打开按钮2.png") no-repeat;
      background-size: 100% 100%;
    }
  }
  .searchArea {
    position: absolute;
    top: 96px;
    right: 200px;
    width: 380px;
    height: 60px;
    background: url("../../../../assets/img/Home/搜索背景切图.png") no-repeat;
    background-size: 100% 100%;
    display: flex;
    direction: row;
    .inputLable {
      padding-left: 50px;
      background: transparent; //去掉背景
      border: none; //去掉边框
      outline: none;
      width: 280px;
      // 提示文字样式
      font-family: "AlibabaPuHuiTi-2-85-Bold";
      font-size: 18px;
      font-weight: normal;
      font-style: italic;
      font-stretch: normal;
      letter-spacing: 0px;
      color: #999999;
    }
    .searchWord {
      width: 100px;
      line-height: 60px;
      font-family: "AlibabaPuHuiTi-2-85-Bold";
      font-size: 18px;
      font-weight: normal;
      font-style: italic;
      font-stretch: normal;
      color: #fff;
      display: flex;
      direction: row;

      .getButton {
        width: 52px;
        margin-left: 10px;
        cursor: pointer;
      }
      .restButton {
        margin-top: 23px;

        width: 15px;
        height: 15px;
        background: url("../../../../assets/img/Home/关闭.png") no-repeat;
        background-size: 100% 100%;
        cursor: pointer;
      }
    }
  }
  .map-legend {
    position: absolute;
    left: 35px;
    bottom: 0;
    width: 166px;
    height: 90px;
    background: url("../../../../assets/img/OneMap/传感器图例.png") no-repeat;
    background-size: 100% 100%;
    z-index: 999;
    pointer-events: none;
  }
  .map-compass {
    position: absolute;
    left: 35px;
    top: 110px;
    width: 30px;
    height: 30px;
    background: url("../../../../assets/img/Home/指北针.png") no-repeat;
    background-size: 100% 100%;
    z-index: 999;
    pointer-events: none;
  }
}
// 去除输入框的默认样式
::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
</style>
